package com.cuitrip.business.user;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cuitrip.apiservice.CommonBusiness;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.app.base.UnitUtils;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.business.user.identity.IdentityMode;
import com.cuitrip.business.user.identity.ImageBitmap;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.business.user.modules.MInput1Activity;
import com.cuitrip.service.R;
import com.cuitrip.util.time.TimeUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.photopicker.DefaultCallback;
import com.lab.photopicker.EasyImage;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.GetImageHelper;
import com.lab.utils.ImageHelper;
import com.lab.utils.MessageUtils;
import com.lab.utils.ToastUtil;
import com.lab.utils.Utils;
import com.lab.utils.imageupload.imp.OssService;
import com.lab.utils.imageupload.model.OssTokenObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.CountryPage;

/**
 * Created on 7/16.
 */
public class SelfIdentificationActivity extends CustomUiFragmentActivity implements CountryPage.OnResult, IProxyCallback {
    public static final String MODE_KEY = "MODE_KEY";

    public static final int REQUEST_CODE_EDIT_USER_REAL_NAME = 1;
    public static final int REQUEST_CODE_EDIT_USER_IDENTITY_NUMBER = 2;
    private static final int REQUEST_CODE_EDIT_USER_COUNTRY = 3;

    public static final int REQUEST_IMAGE_WITDH = 500;
    public static final int REQUEST_IMAGE_HEIGHT = 500;
    @Bind(R.id.ct_not_pass_tv)
    TextView ctNotPassTv;
    @Bind(R.id.ct_user_country_tv)
    TextView ctUserCountryTv;
    @Bind(R.id.ct_user_identity_type_tv)
    TextView ctUserIdentityTypeTv;
    @Bind(R.id.ct_user_identity_number_tv)
    TextView ctUserIdentityNumberTv;
    @Bind(R.id.ct_user_validate_date_tv)
    TextView ctUserValidateDateTv;
    @Bind(R.id.ct_user_birthbay_tv)
    TextView ctUserBirthDayTv;
    @Bind(R.id.ct_identity_one)
    ImageView ctIdentityOne;
    @Bind(R.id.ct_identity_two)
    ImageView ctIdentityTwo;
    @Bind(R.id.iconIdentityOneClear)
    IconTextView iconIdentityOneClear;
    @Bind(R.id.iconIdentityTwoClear)
    IconTextView iconIdentityTwoClear;
    @Bind(R.id.layoutIdentityOne)
    View layoutIdentityOne;
    @Bind(R.id.layoutIdentityTwo)
    View layoutIdentityTwo;
    @Bind(R.id.ct_user_gender_tv)
    TextView ctUserGenderTv;
    @Bind(R.id.ct_user_real_name_tv)
    TextView ctUserRealName;
    @Bind(R.id.ct_identity_add)
    RelativeLayout ctIdentityAd;

    IdentityMode identityMode;
    private static final int REQUEST_IMAGE = 100;
    private static final int REQUEST_IDENTITY = 102;

    ApiProxy apiProxy = new ApiProxy(this);
    private OssService ossService = new OssService();
    boolean isSubmit = false;


    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.GET_MOBILE_OSS_TOKEN.equals(response.getApiName())) {
            if (response.isResponseNormal()) {
                OssTokenObject ossTokenObject = (OssTokenObject) response.result;
                ossService.initClient(ossTokenObject);
            } else {
                if (!TextUtils.isEmpty(response.msg)) {
                    ToastUtil.toast(response.msg);
                }
            }
        } else if (ApiManager.UPLOAD_CREDIT_INFO.equals(response.getApiName())) {
            hideNoCancelDialog();
            if (response.isResponseNormal()) {
                setResult(RESULT_OK);
                MessageUtils.showToast(getString(R.string.user_operation_verify_feedback));
                finish();
                isSubmit = false;
            } else {
                isSubmit = false;
                if (!TextUtils.isEmpty(response.msg)) {
                    ToastUtil.toast(response.msg);
                }
            }
        }
        return false;
    }

    public static void start(Activity context, String feailedReason, String country, String type, String identityNumber, String date, String realName, String gender, String birthDay, String pic1, String pic2) {
        ArrayList<ImageBitmap> bitmaps = new ArrayList<>();
        if (!TextUtils.isEmpty(pic1)) {
            ImageBitmap imageBitmap = new ImageBitmap();
            imageBitmap.setUrl(pic1);
            bitmaps.add(imageBitmap);
        }
        if (!TextUtils.isEmpty(pic2)) {
            ImageBitmap imageBitmap = new ImageBitmap();
            imageBitmap.setUrl(pic2);
            bitmaps.add(imageBitmap);
        }
        IdentityMode indentityMode = new IdentityMode(feailedReason, country, type, identityNumber, date, realName, gender, birthDay, bitmaps);
        context.startActivityForResult(new Intent(context, SelfIdentificationActivity.class)
                .putExtra(MODE_KEY, indentityMode), REQUEST_IDENTITY);
    }

    public static boolean isModifyed(int request, int response, Intent date) {
        return request == REQUEST_IDENTITY && response == RESULT_OK;
    }

    @OnClick(R.id.ct_not_pass_tv)
    public void hideReson() {
        ctNotPassTv.setVisibility(View.GONE);
    }

    public void trySubmit() {
        if (TextUtils.isEmpty(identityMode.getCountry())) {
            shakeView(R.id.ct_user_country_v);
            return;
        }
        if (TextUtils.isEmpty(identityMode.getIdentityType())) {
            shakeView(R.id.ct_user_identity_type_ll);
            return;
        }
        if (TextUtils.isEmpty(identityMode.getIdentityNumber())) {
            shakeView(R.id.ct_user_identity_number_ll);
            return;
        }
        if (TextUtils.isEmpty(identityMode.getIdentityDate())) {
            shakeView(R.id.ct_user_validate_date_ll);
            return;
        }
        if (TextUtils.isEmpty(identityMode.getRealName())) {
            shakeView(R.id.ct_user_real_name_ll);
            return;
        }
        if (TextUtils.isEmpty(identityMode.getGender())) {
            shakeView(R.id.ct_user_gender_ll);
            return;
        }
        if (TextUtils.isEmpty(identityMode.getBirthDay())) {
            shakeView(R.id.ct_user_birthday);
            return;
        }
        if (identityMode.getImages().size() < 2) {
            shakeView(R.id.ct_identity_add);
            return;
        }
        submit();

    }

    private void shakeView(int id) {
        View view = findViewById(id);
        if (view != null) {
            Utils.shakeView(view);
        }
    }

    public void submit() {
        showNoCancelDialog();
        isSubmit = true;
        if (identityMode.isImageUploaded()) {
            UserBusiness.updateIndentity(apiProxy, identityMode);
        } else {
            //wait upload thread
        }
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.user_attribute_id_document);
        config.mTopbarRightAreaName = getString(R.string.operation_submit);
        config.mRightStyle = CustomUiConfig.AreaStyle.TEXT_STYLE;
        return config;
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    @Override
    public void onTopbarRightPress() {
        trySubmit();
    }

    protected void onCreate(Bundle savedInstanceState) {
        identityMode = (IdentityMode) getIntent().getSerializableExtra(MODE_KEY);
        super.onCreate(savedInstanceState, R.layout.ct_my_id);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        render(identityMode);
        CommonBusiness.getMobileOssToken(apiProxy);
    }

    @OnClick(R.id.iconIdentityOneClear)
    public void removeOne() {
        removeBitmap(0);
    }

    @OnClick(R.id.iconIdentityTwoClear)
    public void removeTwo() {
        removeBitmap(1);
    }


    @OnClick(R.id.ct_user_validate_date_ll)
    public void showValidateDate() {
        MessageUtils.showDateCheck(this, new MessageUtils.DateCheckListener() {
            @Override
            public void onDataSelect(String s) {
                long time = TimeUtil.parseString2Long(s, "yyyy-MM-dd");
                ctUserValidateDateTv.setText(TimeUtil.formatDay(ctUserValidateDateTv.getContext(), time));
                identityMode.setIdentityDate(s);
            }
        });
    }

    @OnClick(R.id.ct_user_birthday)
    public void showBirthDay() {
        MessageUtils.showDateCheck(this, new MessageUtils.DateCheckListener() {
            @Override
            public void onDataSelect(String s) {
                long time = TimeUtil.parseString2Long(s, "yyyy-MM-dd");
                ctUserBirthDayTv.setText(TimeUtil.formatDay(ctUserBirthDayTv.getContext(), time));
                identityMode.setBirthDay(s);
            }
        });
    }

    @OnClick(R.id.ct_user_country_v)
    public void showCountry() {
        TrackUtil.trackScreenName("/user/verification/id/set/country");
        Intent intent = new Intent(this, CountryPageSelectActivity.class);
        startActivityForResult(intent, REQUEST_CODE_EDIT_USER_COUNTRY);
    }

    public void removeBitmap(int index) {
        if (identityMode.getImages().size() > index) {
            identityMode.getImages().remove(index);
            render(identityMode);
        }
    }

    @OnClick(R.id.ct_identity_add)
    public void addBitmap() {
        EasyImage.openChooser(this, "", true);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_EDIT_USER_REAL_NAME:
                if (resultCode == RESULT_OK) {
                    String result = data.getStringExtra(MInput1Activity.KEY_RESULT);
                    ctUserRealName.setText(result);
                    identityMode.setRealName(result);
                }
                return;
            case REQUEST_CODE_EDIT_USER_COUNTRY:
                if (resultCode == RESULT_OK) {
                    String result = data.getStringExtra(CountryPageSelectActivity.KEY_RESULT);
                    ctUserCountryTv.setText(result);
                    identityMode.setCountry(result);
                }
                return;
            case REQUEST_CODE_EDIT_USER_IDENTITY_NUMBER:
                if (resultCode == RESULT_OK) {
                    String result = data.getStringExtra(MInput1Activity.KEY_RESULT);
                    ctUserIdentityNumberTv.setText(result);
                    identityMode.setIdentityNumber(result);
                }
                return;

        }

        EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source) {
                //Some error handling
            }

            @Override
            public void onImagePicked(File imageFile, EasyImage.ImageSource source) {
                //Handle the image
                Bitmap bp = GetImageHelper.getResizedBitmap(SelfIdentificationActivity.this, Uri.fromFile(imageFile), REQUEST_IMAGE_WITDH, REQUEST_IMAGE_HEIGHT);
                if (bp == null) {
                } else {
                    ImageBitmap imageBitmap = new ImageBitmap();
                    imageBitmap.setBitmap(bp);
                    identityMode.getImages().add(imageBitmap);
                    uploadBitmap(imageBitmap, imageFile);
                    render(identityMode);
                }
            }

            @Override
            public void onCanceled(EasyImage.ImageSource source) {
                //Cancel handling, you might wanna remove taken photo if it was canceled
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(AppCoreRuntime.context);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });
    }

    public void uploadBitmap(final ImageBitmap imageBitmap, File file) {
        CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
        ossService.asyncPutImage(OssService.getObjectName(userInfo.getUid(), file), file.getAbsolutePath(), new OssService.UploadCallback() {
            @Override
            public void onFailure(String errorMessage) {
                MessageUtils.showToast(getString(R.string.feedback_upload_fail));
                identityMode.getImages().remove(imageBitmap);
                render(identityMode);
                if (isSubmit) {
                    hideNoCancelDialog();
                    isSubmit = false;
                }
            }

            @Override
            public void onSuccess(String url) {
                imageBitmap.setUrl(url);
                if (isSubmit) {
                    trySubmit();
                }
            }

            @Override
            public void onProgress(int progress) {
            }
        });
    }

    public String getIdentityType(String code) {
        return UnitUtils.getIndentityName(code);
    }

    public void setImage(ImageView view, ImageBitmap imageBitmap) {
        if (TextUtils.isEmpty(imageBitmap.getUrl())) {
            view.setImageBitmap(imageBitmap.getBitmap());
        } else {
            ImageHelper.displayCtImage(imageBitmap.getUrl(), view, null);
        }
    }

    @OnClick(R.id.ct_user_identity_type_ll)
    public void showIdentityType() {
        AlertDialog.Builder builder = MessageUtils.createHoloBuilder(this);
        builder.setAdapter(new ArrayAdapter<>(this, R.layout.ct_choice_item, R.id.checktext,
                getResources().getStringArray(R.array.ct_identity_types)), new Dialog.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (i < getResources().getStringArray(R.array.ct_identity_types).length) {
                    identityMode.setIdentity(
                            UnitUtils.getIndentityCode(
                                    getResources().getStringArray(R.array.ct_identity_types)[i])
                    );
                    render(identityMode);
                }
            }
        });
        AlertDialog dialog = builder.show();
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.height = getResources().getDimensionPixelOffset(R.dimen.ct_dp_240); // 高度
        window.setAttributes(lp);
    }

    @OnClick(R.id.ct_user_gender_ll)
    public void showUserGender() {
        AlertDialog.Builder builder = MessageUtils.createHoloBuilder(this);
        builder.setAdapter(new ArrayAdapter<String>(this, R.layout.ct_choice_item, R.id.checktext,
                getResources().getStringArray(R.array.ct_gender_list)), new Dialog.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String result = getResources().getStringArray(R.array.ct_gender_list)[i];
                ctUserGenderTv.setText(result);
                identityMode.setGender((i + 1) + "");
            }
        });
        AlertDialog dialog = builder.show();
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.height = getResources().getDimensionPixelOffset(R.dimen.ct_dp_240); // 高度
        window.setAttributes(lp);
    }

    protected void render(IdentityMode identityMode) {
        if (TextUtils.isEmpty(identityMode.getFailedReaon())) {
            ctNotPassTv.setVisibility(View.GONE);
        } else {
            ctNotPassTv.setVisibility(View.VISIBLE);
            ctNotPassTv.setText(identityMode.getFailedReaon());
        }

        ctUserCountryTv.setText(identityMode.getCountry());
        String identityType = getIdentityType(identityMode.getIdentityType());
        if (TextUtils.isEmpty(identityType)) {
            ctUserIdentityTypeTv.setText(getString(R.string.user_attribute_id_document_type_value_idcard));
            identityMode.setIdentity(getString(R.string.user_attribute_id_document_type_value_idcard));
        } else {
            ctUserIdentityTypeTv.setText(identityType);
        }
        //判断是否为yyyy-MM-dd
        String format = "yyyy-MM-dd";
        long validateDate = TimeUtil.parseString2Long(identityMode.getIdentityDate(), format);
        if (validateDate > 0) {
            ctUserValidateDateTv.setText(TimeUtil.formatDay(ctUserValidateDateTv.getContext(), validateDate));
        }
        ctUserIdentityNumberTv.setText(identityMode.getIdentityNumber());
        ctUserRealName.setText(identityMode.getRealName());
        ctUserGenderTv.setText(identityMode.getGender().equals("1") ? getString(R.string.filter_option_insider_value_male) : getString(R.string.filter_option_insider_value_female));
        long birthDate = TimeUtil.parseString2Long(identityMode.getBirthDay(), format);
        if (birthDate > 0) {
            ctUserBirthDayTv.setText(TimeUtil.formatDay(ctUserBirthDayTv.getContext(), birthDate));
        }
        switch (identityMode.getImages().size()) {
            case 0:
                layoutIdentityOne.setVisibility(View.GONE);
                layoutIdentityTwo.setVisibility(View.GONE);
                ctIdentityAd.setVisibility(View.VISIBLE);
                break;
            case 1:
                layoutIdentityOne.setVisibility(View.VISIBLE);
                setImage(ctIdentityOne, identityMode.getImages().get(0));
                layoutIdentityTwo.setVisibility(View.GONE);
                ctIdentityAd.setVisibility(View.VISIBLE);
                break;
            default:
                layoutIdentityOne.setVisibility(View.VISIBLE);
                setImage(ctIdentityOne, identityMode.getImages().get(0));
                layoutIdentityTwo.setVisibility(View.VISIBLE);
                setImage(ctIdentityTwo, identityMode.getImages().get(1));
                ctIdentityAd.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void onResult(HashMap<String, Object> data) {
        if (data != null) {
            int page = (Integer) data.get("page");
            if (page == 1) {
                // 国家列表返回
                String currentId = (String) data.get("id");
                if (!TextUtils.isEmpty(currentId)) {
//                HashMap<String, String>  countryRules = (HashMap<String, String>) data.get("rules");
                    String[] country = SMSSDK.getCountry(currentId);
                    if (country != null) {
                        ctUserCountryTv.setText(country[0]);
                        identityMode.setCountry(country[0]);
                    }
                }
            }
        }
    }

    @OnClick(R.id.ct_user_identity_number_ll)
    public void editIdentityNumber() {
        Bundle bundle = new Bundle();
        bundle.putString(MInput1Activity.KEY_VALUE, ctUserIdentityNumberTv.getText().toString());
        bundle.putInt(MInput1Activity.KEY_VALUE_MAX_LENGTH, 50);
        bundle.putString(MInput1Activity.KEY_TITLE, getString(R.string.user_attribute_id_document_number));
        bundle.putString(MInput1Activity.KEY_TIP, getString(R.string.user_attribute_id_document_number_limit));
        MInput1Activity.startEditActivityForResult(this,
                bundle,//入参
                REQUEST_CODE_EDIT_USER_IDENTITY_NUMBER);
        TrackUtil.trackScreenName("/user/verification/id/set/id_number");
    }

    @OnClick(R.id.ct_user_real_name_ll)
    public void editUserRealName() {
        Bundle bundle = new Bundle();
        bundle.putString(MInput1Activity.KEY_VALUE, ctUserRealName.getText().toString());
        bundle.putInt(MInput1Activity.KEY_VALUE_MAX_LENGTH, 100);
        bundle.putString(MInput1Activity.KEY_PLACE_HOLDER, getString(R.string.user_attribute_name_limit));
        bundle.putString(MInput1Activity.KEY_TITLE, getString(R.string.user_attribute_name));
        bundle.putString(MInput1Activity.KEY_TIP, "");
        TrackUtil.trackScreenName("/user/verification/id/set/name");
        MInput1Activity.startEditActivityForResult(this,
                bundle,//入参
                REQUEST_CODE_EDIT_USER_REAL_NAME);
    }
}
